from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, render
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from opman.models import Flowline, Process, Server_Assets
import time
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_protect
import json
import paramiko, sys

def list(request):
	if request.method == "GET":
		oFlowline = Flowline.objects.all()

	return render(request, 'flowline/list.html', {'oFlowline': oFlowline})
	#return HttpResponse("")

@csrf_protect
def add_flowline(request):
	if request.method == 'POST':
		oFlowline = Flowline(
			flowline_name = request.POST['flowline_name'],
			create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
			founder_id = int(request.session['_auth_user_id'])
		)
		oFlowline.save()

		if oFlowline.id:
			receipt = 1
		else:
			receipt = 2

	return HttpResponse(receipt)

def process_list(request):
	oFlowline = Flowline.objects.all()
	serverList = Server_Assets.objects.all()
	processList = Process.objects.all()
	
	treeProcess = []
	prname = ''
	treeName = []

	for flowline in oFlowline:
		prname = ''
		for process in processList:
			
			if process.flowline_id == flowline.id:
				prname = prname  + process.process_name + ' -- '
				
	
		treeName.insert(flowline.id, flowline.flowline_name)
		treeProcess.insert(flowline.id, prname)


	return render(request, 'flowline/process_list.html', 
		{
			'oFlowline': oFlowline, 
			'serverList': serverList, 
			'processList': processList, 
			'treeName': treeName,
			'treeProcess': treeProcess
		}
	)

@csrf_protect
def process_add(request):
	if request.method == 'POST':

		oProcess = Process(
			process_name = request.POST['process_name'],
			abbreviation_name = request.POST['abbreviation'],
			flowline_id = request.POST['flowline_id'],
			macking_host = request.POST['host'],
			execution_statement = request.POST['execution_statement'],
			last_process = request.POST['last_process'],
			create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
			founder_id = int(request.session['_auth_user_id'])
		)
		oProcess.save()

		if oProcess.id:
			receipt = 1
		else:
			receipt = 2

	return HttpResponse(receipt)


def process_edit(request):
	pass

# 作业
def task(request):
	pass


def add_task(request):
	pass



# 流程操作

def macking(request):
	oFlowline = Flowline.objects.all()
	serverList = Server_Assets.objects.all()
	processList = Process.objects.all()
	
	treeProcess = {}
	prname = {}
	treeName = []

	for flowline in oFlowline:
		prname = {}
		for process in processList:
			if process.flowline_id == flowline.id:
				prname.update({str(process.id): process.process_name})
				
				treeProcess.update(
					{
					str(flowline.id): {
						'flowline_name': flowline.flowline_name,
						'process_list': prname
					}
				})
			
	return render(request, 'flowline/macking.html', 
		{
			'treeProcess': treeProcess
		}
	)	

def get_macking_process(request):
	receipt = {}
	alongProcessList = {}
	if request.method == 'POST':
		processList = Process.objects.filter(flowline_id = int(request.POST['flowline_id']))

		for proV in processList:
			alongProcessList.update({
					str(proV.last_process): 
					{
						'process_id': proV.id,
						'process_name': proV.process_name,
						'abbreviation_name': proV.abbreviation_name
					}
				})
				
	receipt = json.dumps({"status": 1, "alongProcessList": alongProcessList})
	return HttpResponse(receipt)


def exec_macking(request):
	receipt = {}
	if request.method == 'POST':
		theProcess = Process.objects.get(id = request.POST['process_id'])
		hostInfo = Server_Assets.objects.get(id = theProcess.macking_host)

		hostip = hostInfo.ip
		client = paramiko.SSHClient()  # 绑定实例

		client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
		client.connect(str(hostInfo.ip), str(hostInfo.port), str(hostInfo.username), str(hostInfo.passwd), timeout=15)

		stdin, stdout, stderr = client.exec_command(str(theProcess.execution_statement))   # 执行bash命令
		result = stdout.read()
		error = stderr.read()

		if not result:
		   receipt = {"status": 2}
		else:
		   receipt = {"status": 1}

		client.close()

	return HttpResponse(json.dumps(receipt))


# 操作日志
def macking_log(request):
	pass
